<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>01-引出声明周期</title>
  </head>
  <body>
    <div id="app"></div>

    <!-- 导入 react 主库 -->
    <script src="../js/react.development.js"></script>
    <!-- 导入 reactDom 扩展库 -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 导入 babel 用于将jsx转为js -->
    <script src="../js/babel.min.js"></script>
    <!-- 导入 prop-types 用于对组件标签属性进行限制 -->
    <script src="../js//prop-types.js"></script>

    <script type="text/babel">
      class Life extends React.Component {
        state = {
          opacity: 1,
        };

        death = () => {
          // 卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById("app"));
        };

        // 组件挂载完毕
        componentDidMount() {
          this.timer = setInterval(() => {
            let { opacity } = this.state;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity });
          }, 200);
        }

        // 组件卸载之前
        componentWillUnmount() {
          // 组件卸载之前清楚定时器
          clearInterval(this.timer);
        }

        render() {
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>react学不会怎么办</h2>
              <button onClick={this.death}>不活了</button>
            </div>
          );
        }
      }
      ReactDOM.render(<Life />, document.getElementById("app"));
    </script>
  </body>
</html>
